//
//  Utility.m
//  Iain Banks
//
//  Created by thohd/Sinbad Flyce on 20/05/2010 - 2012.
//  Copyright 2010 iNIL/ABOM. All rights reserved.
//

#import "Utility.h"


@implementation Utility

+ (void) showAlert: (NSString*) msg
{
	[[[[UIAlertView alloc] initWithTitle: nil
								 message: msg
								delegate: nil
					   cancelButtonTitle: @"OK"
					   otherButtonTitles: nil] autorelease] show];
}

@end


@implementation JGoUtility

static NSMutableDictionary *sharedCreateAccount = nil;
static NSMutableArray *sharedUniversities = nil;
static NSMutableArray *sharedCourses = nil;
static NSMutableArray *sharedColleges = nil;
static NSMutableArray *sharedModules = nil;
static CLLocation *sharedLocation = nil;
static NSLock *sharedLock = nil;
static NSMutableDictionary *sharedCachedAvatars = nil;
static UIViewController* sharedRootViewController = nil;

// Function API

+ (CGFloat)widthFromString:(NSString*)aString font:(UIFont*)aFont
{
	CGSize maximumLabelSize = CGSizeMake(999,42);
	CGSize sz = [aString sizeWithFont:aFont constrainedToSize:maximumLabelSize 
                        lineBreakMode:UILineBreakModeWordWrap];
    
    return sz.width;    
}

+ (CGFloat)heightFromString:(NSString*)aString font:(UIFont*)aFont
{
	CGSize maximumLabelSize = CGSizeMake(320,999);
	CGSize sz = [aString sizeWithFont:aFont constrainedToSize:maximumLabelSize 
                        lineBreakMode:UILineBreakModeWordWrap];
    
    return sz.height;    
}

+ (CGFloat)heightFromString:(NSString*)aString maxWidth:(CGFloat)maxWidth font:(UIFont*)aFont
{
	CGSize maximumLabelSize = CGSizeMake(maxWidth,999);
	CGSize sz = [aString sizeWithFont:aFont constrainedToSize:maximumLabelSize 
                        lineBreakMode:UILineBreakModeTailTruncation];
    
    return sz.height;       
}

+ (BOOL)validateEmail:(NSString *)candidate 
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
    
    return [emailTest evaluateWithObject:candidate];
}

+ (void)showAlert:(NSString*)msg
{
	[[[[UIAlertView alloc] initWithTitle: @"Alumnee"
								 message: msg
								delegate: nil
					   cancelButtonTitle: @"OK"
					   otherButtonTitles: nil] autorelease] show];
}

+ (MBProgressHUD*)showProgressInView:(UIView*)view target:(id)aTarget 
                               title:(NSString*)titleText selector:(SEL)aSelector
{
    MBProgressHUD* mbhub = [[[MBProgressHUD alloc] initWithView:view] autorelease];	
	mbhub.labelText = titleText;
    mbhub.removeFromSuperViewOnHide = YES;
    [mbhub setDelegate:(id)view];
	[mbhub show:YES];    
	[view addSubview:mbhub];		    
    [aTarget performSelector:aSelector withObject:mbhub afterDelay:0.3];
    return mbhub;            
}

+ (NSString*)stringFromDate1:(NSDate*)aDate
{
    if (aDate == nil || ![aDate isKindOfClass:[NSDate class]]) {
        return @"0000-00-00";
    }
    
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    dateFormatter.dateFormat = @"yyyy-MM-dd";                
    NSString *stringDate = [dateFormatter stringFromDate:aDate];
    
    return stringDate;    
}

+ (NSString*)stringFromDate2:(NSDate*)aDate
{
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    dateFormatter.dateFormat = @"YYYY";                
    NSString *stringDate = [dateFormatter stringFromDate:aDate];
    
    return stringDate;    
}

+ (NSString*)stringFromDate3:(NSDate*)aDate
{
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    dateFormatter.dateFormat = @"MMM, dd";                
    NSString *stringDate = [dateFormatter stringFromDate:aDate];
    
    return stringDate;        
}

+ (NSString*)stringFromDate4:(NSDate*)aDate
{
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    dateFormatter.dateFormat = @"dd.MM.YY";                
    NSString *stringDate = [dateFormatter stringFromDate:aDate];
    
    return stringDate;        
}

+ (NSString*)stringFromDate5:(NSDate*)aDate
{
    if (![aDate isKindOfClass:[NSDate class]]) {
        return nil;
    }
    
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    dateFormatter.dateFormat = @"hh:mm";                
    NSString *stringDate = [dateFormatter stringFromDate:aDate];
    
    return stringDate; 
}

+ (NSString*)stringFromDate6:(NSDate*)aDate
{
    if (![aDate isKindOfClass:[NSDate class]]) {
        return nil;
    }
    
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
    NSString *stringDate = [dateFormatter stringFromDate:aDate];
    
    return stringDate; 
}

+ (NSString*)stringFromDate7:(NSDate*)aDate
{
    if (![aDate isKindOfClass:[NSDate class]]) {
        return nil;
    }
    
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    dateFormatter.dateFormat = @"yyyy-MM-dd'_'HH:mm:ss";
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
    NSString *stringDate = [dateFormatter stringFromDate:aDate];
    
    return stringDate;
}

+ (NSString*)stringFromArray:(NSArray*)aArrayString
{
    NSString *returnStrings = nil;
    
    for (NSString *aString in aArrayString) {
        
        if (returnStrings == nil) {
            returnStrings = aString;
        }
        else {
            returnStrings = [NSString stringWithFormat:@"%@;%@",returnStrings,aString];
        }
    }
    
    return returnStrings;
}

+ (NSString*)stringForRelationshipStatus:(NSInteger)status
{
    switch (status) {
        case 0:      
            return @"Happy Single";
            break;            
        case 1:    
            return @"Engaged";
            break;            
        case 2:     
            return @"Married";
            break;            
        case 3: 
            return @"Wouldn't You Like";
            break;                        
    }
    
    return nil;
}

+ (NSDate*)dateFromString1:(NSString*)stringDate
{
    if ([stringDate isKindOfClass:[NSDate class]]) {
        return (id)stringDate;
    }
    
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];    
    dateFormatter.dateFormat = @"yyyy-MM-dd";               
    
    NSDate *date = [dateFormatter dateFromString:stringDate];
    
    return date;
}

+ (NSDate*)dateFromString2:(NSString*)stringDate
{
    if ([stringDate isKindOfClass:[NSDate class]]) {
        return (id)stringDate;
    }
    
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];    
    dateFormatter.dateFormat = @"YYYY";               
    
    NSDate *date = [dateFormatter dateFromString:stringDate];
    
    return date;
}

+ (NSDate*)dateFromString3:(NSString*)stringDate
{
    if ([stringDate isKindOfClass:[NSDate class]]) {
        return (id)stringDate;
    }
    //2012-09-18 15:10:05
    NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];    
    dateFormatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";               
    
    NSDate *date = [dateFormatter dateFromString:stringDate];
    
    return date;    
}

+ (NSString*)longTimeToShortTime:(NSString*)longTime
{    
    if (![longTime isKindOfClass:[NSString class]]) {
        return nil;
    }
    
    NSArray *arrayString = [longTime componentsSeparatedByString:@":"];
    
    if ([arrayString count] == 3) {
        NSString *shortTime = [NSString stringWithFormat:@"%@:%@",
                               [arrayString objectAtIndex:0],
                               [arrayString objectAtIndex:1]];
        return shortTime;
    }
    
    return nil;
}

+ (NSString*)distanceString:(NSString*)meterString
{
    CGFloat fmeters = [meterString floatValue];
    NSInteger imeter = (NSInteger)fmeters;
    
    if (imeter < 1000) {
        return [NSString stringWithFormat:@"%dm",imeter];
    }
    else if (imeter >= 1000) {
        imeter = imeter / 1000;        
        return [NSString stringWithFormat:@"%dkm",imeter];
    }
    
    return nil;
}

+ (NSInteger)daysBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime
{
    NSDate *fromDate;
    NSDate *toDate;
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    [calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate
                 interval:NULL forDate:fromDateTime];
    [calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate
                 interval:NULL forDate:toDateTime];
    
    NSDateComponents *difference = [calendar components:NSDayCalendarUnit
                                               fromDate:fromDate toDate:toDate options:0];
    
    return [difference day];
}

+ (NSInteger)weekOfYearFromDate:(NSDate*)aDate
{
    //unsigned units = NSWeekCalendarUnit;
    //NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    //NSDateComponents *components = [gregorian components:units fromDate:aDate];
    
    NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
    [dateFormat setDateFormat:@"ww"];
    NSString *weeknumber = [dateFormat stringFromDate: aDate];
    
    return [weeknumber integerValue];
}

+ (void)setUniversities:(NSArray*)universities
{
    [sharedUniversities release];
    sharedUniversities = (id)[universities retain];
}

+ (void)setCourses:(NSArray*)courses
{
    [sharedCourses release];    
    sharedCourses = (id)[courses retain];
}

+ (void)setColleges:(NSArray*)colleges
{
    [sharedColleges release];
    sharedColleges = (id)[colleges retain];
}

+ (void)setModules:(NSArray*)modules;
{
    [sharedModules release];
    sharedModules = (id)[modules retain];
}

+ (void)setLocation:(CLLocation*)location
{
    [sharedLocation release];
    sharedLocation = [location retain];
}

+ (UIView*)frontFromView:(UIView*)aView
{
    UIWindow* tempWindow  = nil;
    UIView *keyboard = nil;
    
    if ([[[UIApplication sharedApplication] windows] count] > 1) {
        tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
        keyboard = [tempWindow.subviews objectAtIndex:0];
    }
    
    return (keyboard != nil ? tempWindow : aView);
}

+ (void)setSharedRootViewController:(UIViewController*)viewController
{
    sharedRootViewController = viewController;
}

// Shared Data

+ (NSMutableDictionary*)sharedCreateAccount
{
    if (sharedCreateAccount == nil) {
        sharedCreateAccount = [NSMutableDictionary new];
        
        [sharedCreateAccount setValue:@"" forKey:@"name"];
        [sharedCreateAccount setValue:@"" forKey:@"dob"];
        [sharedCreateAccount setValue:@"1" forKey:@"gender"]; 
        [sharedCreateAccount setValue:@"" forKey:@"email"]; 
        [sharedCreateAccount setValue:@"" forKey:@"password"]; 
        [sharedCreateAccount setValue:@"" forKey:@"college"]; 
        [sharedCreateAccount setValue:@"" forKey:@"university"]; 
        [sharedCreateAccount setValue:nil forKey:@"course"]; 
        [sharedCreateAccount setValue:@"" forKey:@"u_year"]; 
        [sharedCreateAccount setValue:@"" forKey:@"c_year"];         
        [sharedCreateAccount setValue:@"" forKey:@"degree"]; 
        [sharedCreateAccount setValue:nil forKey:@"modules"];
        [sharedCreateAccount setValue:@"0" forKey:@"status"];
        [sharedCreateAccount setValue:@"" forKey:@"thumb"];
    }
    
    NSDictionary *settings = [sharedCreateAccount objectForKey:@"setting"];
    
    if (settings == nil) {
        settings = [[NSMutableDictionary new] autorelease];
        [settings setValue:@"1" forKey:@"status"];
        [settings setValue:@"1" forKey:@"course"];
        [settings setValue:@"1" forKey:@"u_year"];
        [settings setValue:@"1" forKey:@"modules"];
        [settings setValue:@"1" forKey:@"college"];   
        [sharedCreateAccount setValue:settings forKey:@"setting"];
    }
    
    return sharedCreateAccount;
}

+ (void)copySharedCreateAccount:(NSDictionary*)aCreateAccount
{    
    [sharedCreateAccount release];
    sharedCreateAccount = [aCreateAccount mutableCopy];
    
    NSDictionary *settings = [sharedCreateAccount objectForKey:@"setting"];
    
    if (settings == nil) {
        settings = [[NSMutableDictionary new] autorelease];
        [settings setValue:@"1" forKey:@"status"];
        [settings setValue:@"1" forKey:@"course"];
        [settings setValue:@"1" forKey:@"u_year"];
        [settings setValue:@"1" forKey:@"modules"];
        [settings setValue:@"1" forKey:@"college"];   
        [sharedCreateAccount setValue:settings forKey:@"setting"];
    }
    else {
        NSDictionary *settingsCopy = [[settings mutableCopy] autorelease];
        [sharedCreateAccount setValue:settingsCopy forKey:@"setting"];
    }
}

+ (NSMutableDictionary*)mutableCopyFromCreateAccount
{
    NSMutableDictionary *createAccountCopy = [[sharedCreateAccount mutableCopy] autorelease];
    
    NSDictionary *settings = [sharedCreateAccount objectForKey:@"setting"];
    
    if (settings == nil) {
        settings = [[NSMutableDictionary new] autorelease];
        [settings setValue:@"1" forKey:@"status"];
        [settings setValue:@"1" forKey:@"course"];
        [settings setValue:@"1" forKey:@"u_year"];
        [settings setValue:@"1" forKey:@"modules"];
        [settings setValue:@"1" forKey:@"college"];   
        [createAccountCopy setValue:settings forKey:@"setting"];
    }
    else {
        NSDictionary *settingsCopy = [[settings mutableCopy] autorelease];
        [createAccountCopy setValue:settingsCopy forKey:@"setting"];
    }
    
    return createAccountCopy;
}

+ (NSMutableArray*)sharedUniversities
{
    return sharedUniversities;
}

+ (NSMutableArray*)sharedCourses
{
    return sharedCourses;
}

+ (NSMutableArray*)sharedColleges
{
    return sharedColleges;
}

+ (NSMutableArray*)sharedModules
{
    return sharedModules;
}

+ (CLLocation*)sharedLocation
{
    return sharedLocation;
}

+ (NSString*)sharedLatitude
{
    NSString *latString = @"20.8339191";
    
    if ([JGoUtility sharedLocation]) {
        latString = [NSString stringWithFormat:@"%f",[JGoUtility sharedLocation].coordinate.latitude];
    }
    
    return latString;
}

+ (NSString*)sharedLongitude
{
    NSString *lonString = @"105.8664700";
    
    if ([JGoUtility sharedLocation]) {
        lonString = [NSString stringWithFormat:@"%f",[JGoUtility sharedLocation].coordinate.longitude];
    }
    
    return lonString;
}

+ (NSString*)sharedUCCM
{
    return nil;
}

+ (NSLock*)sharedLock
{
    if (sharedLock == nil) {
        sharedLock = [[NSLock alloc] init];
    }
    
    return sharedLock;
}

+ (NSMutableDictionary*)sharedCachedAvatars
{
    if (sharedCachedAvatars == nil) {
        sharedCachedAvatars = [NSMutableDictionary new];
    }
    
    return sharedCachedAvatars;
}

+ (UIViewController*)sharedRootViewController
{
    return sharedRootViewController;
}

@end